package org.gitee.lz.xspring.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.tigerbrokers.bff.apihub.common.dto.pojo.v1.response.ExecResult;
import io.vertx.core.json.Json;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;

/**.
 * @ClassName: HttpClientUtils
 * @Description: OkHttp3 client
 * @Author: lizhen
 * @Date: 2023-12-21 20:11
 * @Version: 1.0
 **/
@Component
@Slf4j
public class HttpClientUtils {

  /**.
   * OkHttps Get方法
   * @param url not null
   * @param connectTimeOutSec not null
   * @param callTimeoutSec not null
   * @return Response
   * @throws IOException not null
   */
  public ExecResult doGet(String url, int connectTimeOutSec, int callTimeoutSec)
      throws IOException {
    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(connectTimeOutSec, TimeUnit.SECONDS)
        .callTimeout(callTimeoutSec, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build();

    Request request = new Request.Builder()
        .url(url)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
      log.error("err: {}, response: {}", ExecResult.MSG_HTTP_CLIENT_FAIL, response);
      throw new RuntimeException(ExecResult.MSG_HTTP_CLIENT_FAIL);
    }

    if (response.body() == null) {
      log.error("return body is null. response: {}", response);
      throw new RuntimeException(ExecResult.MSG_HTTP_CLIENT_FAIL);
    }

    ExecResult execResult = Json.decodeValue(response.body().string(), ExecResult.class);
    if (!execResult.isSuccess()) {
      log.error("get task config failed, msg: {}", execResult.getMessage());
      throw new RuntimeException(ExecResult.MSG_HTTP_CLIENT_FAIL);
    }

    return execResult;
  }
}
